using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class LevelPanel : BasePanel
{
    public Transform levelSelect;
    public Transform level;
    public Text starCount;
    public Button backButton;
    public Transform stars;

    public override void OnInit()
    {
        skinPath = "LevelPanel";
        layer = PanelManager.Layer.Panel;
    }

    public override void OnShow()
    {
        // 寻找组件
        level = skin.transform.Find("Level");
        levelSelect = skin.transform.Find("LevelSelect");
        starCount = skin.transform.Find("StarCount").GetComponent<Text>();
        backButton = skin.transform.Find("BackButton").GetComponent<Button>();

        starCount.text = PlayerPrefs.GetInt("Total").ToString();

        GenerateLevel();

        backButton.onClick.AddListener(OnBackClick);
    }

    public override void OnClose() { }

    private void OnBackClick()
    {
        Close();
        SceneManager.LoadScene(0);
    }

    private void GenerateLevel()
    {
        for (int i = 0; i < 3; i++)
        {
            GameObject go = Instantiate(level.gameObject, levelSelect);
            go.name = (i + 1).ToString();

            stars = go.transform.Find("Stars");
            CheckStarCount(go.name);

            Button button = go.GetComponent<Button>();
            button.onClick.AddListener(() =>
            {
                Close();
                SceneManager.LoadScene("Level " + go.name);
            });

            Text text = go.transform.Find("Text").GetComponent<Text>();
            text.text = (i + 1).ToString();

            go.SetActive(true);
        }
    }

    private void CheckStarCount(string name)
    {
        if (!PlayerPrefs.HasKey("Level " + name))
            return;
        int count = PlayerPrefs.GetInt("Level " + name);
        Debug.Log("count");
        Debug.Log(count);
        stars.GetChild(count).gameObject.SetActive(true);
    }
}
